package utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.http.HttpResponse;

@WebFilter(filterName = "userFilter", urlPatterns = "/pc/*")
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse =(HttpServletResponse)servletResponse;
        Object user = httpServletRequest.getSession().getAttribute("user");//Attribute是在Servlet程序中给的
        String url = httpServletRequest.getRequestURI();
        String contextPath = httpServletRequest.getContextPath();
        if(url.equals(contextPath + "/pc/web_login.jsp") ||url.contains("lib") || url.contains("static")){
            filterChain.doFilter(servletRequest, servletResponse);
        }
        else {
            if (user == null) {
                httpServletRequest.getRequestDispatcher("/pc/web_login.jsp").forward(servletRequest,servletResponse);
            } else {
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
